package com.roc.web.action.settlemorg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.OrgSettlementBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblSettleItem;
import com.roc.service.IAccountBalanceService;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OrgPayStatus;
import com.roc.util.constant.PayStatus;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/orgpay")
public class SettlementOrgPayAction extends PaginationBaseAction{
	private static final long serialVersionUID = 1L;
	private SettlementOrgPaySearchCondition searchCondition;
	private static Logger logger = LogManager.getLogger(SettlementOrgPayAction.class);
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	private InputStream excelFile;
	@Autowired
	private IPagenitionService pagenitionService;
	@Autowired
	private IExcelService excelService;
	@Autowired
	private IAccountBalanceService service;
	/**
	 * 初始化出款页面
	 * @return
	 */
	@Action(value="queryToPayInit",results={@Result(name="success",location="/pages/settlementOrg/orgPayMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryToPayMoneyJsp(){
		try {
				Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_COMM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())) {
					searchCondition=new SettlementOrgPaySearchCondition();
					String today = Constance.currTime();
					searchCondition.setApplyDateMin(today);
					searchCondition.setApplyDateMax(today);
					List<TblInsInf> queryOrgList= service.loadOrgCode();
					if(queryOrgList!=null){
						orgList.addAll(queryOrgList);
					}
					return SUCCESS;
				}
				addActionError("无权限访问!!!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionError("初始化出款查询页面异常");
			return ERROR;
		}
		return ERROR;
	}
	/**
	 * 出款列表
	 * @return
	 */
	@Action(value="queryToPayMoneyJsp",results={@Result(name="success",location="/pages/settlementOrg/orgPayMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String querySettlementMsgList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_COMM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementOrgPaySearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementOrgPaySearchCondition();
					}
				}
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				
				List<OrgSettlementBean> settleList = new ArrayList<OrgSettlementBean>();
				dealTheSearchRsList(searchRsList,settleList);
				addActionMessage("当前条件下统计到【"+rows+"】条记录");
				getRequest().setAttribute("settleList", settleList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error("出款查询异常",e);
			addActionError("出款查询异常");
			return ERROR;
		}
		return ERROR;
	}
	private void dealTheSearchRsList(List<Object> searchRsList,
		List<OrgSettlementBean> settleList) throws Exception {
			try {
				if(searchRsList != null && searchRsList.size() > 0){
					Iterator<Object> it = searchRsList.iterator();
					while(it.hasNext()){
						Object[] obj = (Object[]) it.next();					
						OrgSettlementBean bean=new OrgSettlementBean();
						bean.setSettleDate(Constance.Null2EmptyTrim(obj[0]));
						bean.setKeyRsp(Constance.Null2EmptyTrim(obj[1]));
						bean.setTransCd(OrgPayStatus.valueOfCode(Constance.Null2EmptyTrim(obj[2])).getName());
						bean.setOrgCode(Constance.Null2EmptyTrim(obj[3]));
						bean.setAccountNo(Constance.Null2EmptyTrim(obj[4]));
						bean.setMobileNo(Constance.Null2EmptyTrim(obj[5]));
						String num=Constance.Null2EmptyTrim(obj[6]);
						if(!"".equals(num)){
							bean.setTotalNum(Integer.parseInt(num));
						}else{
							bean.setTotalNum(1);
						}
						String amt=Constance.Null2EmptyTrim(obj[7]);
						if(!"".equals(amt)){
							bean.setAmt(Double.parseDouble(amt));
						}else{
							bean.setAmt(0.00);
						}
						String fee=Constance.Null2EmptyTrim(obj[8]);
						if(!"".equals(fee)){
							bean.setFee(Double.parseDouble(fee));
						}else{
							bean.setFee(0.00);
						}
						bean.setAcctNo(Constance.Null2EmptyTrim(obj[9]));
						bean.setAcctName(Constance.Null2EmptyTrim(obj[10]));
						bean.setStatus(OrgPayStatus.valueOfCode(Constance.Null2EmptyTrim(obj[11])).getName());
						bean.setRemark1(Constance.Null2EmptyTrim(obj[12]));
						bean.setRemark6(Constance.Null2EmptyTrim(obj[13]));
						bean.setBankName(Constance.Null2EmptyTrim(obj[14]));
						bean.setTranSeq(Constance.Null2EmptyTrim(obj[15]));
						settleList.add(bean);					
					}
			}
		}catch (Exception e) {
			throw new Exception("解析数据封装到出款信息实体类异常");
		}
	}
	
	@Action(value = "exportInit", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String exportFreezeMcht() throws Exception {

		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_COMM.getCode())
					|| op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementOrgPaySearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementOrgPaySearchCondition();
					}
				}

				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition,0,rows);
				}
				
				List<OrgSettlementBean> settleList = new ArrayList<OrgSettlementBean>();
				dealTheSearchRsList(searchRsList,settleList);
				
				logger.info("开始导出出款信息~");
				SXSSFWorkbook work = excelService.exportOrgApplyMoneyList(settleList);
	
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);
	
				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
				logger.info("导出出款信息成功~");	
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return ERROR;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ORG_PAY_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettlementOrgPaySearchCondition)getSession().getAttribute(SEARCH_SESSION_ORG_PAY_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public SettlementOrgPaySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			SettlementOrgPaySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName = "机构出款信息" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}
	public List<TblInsInf> getOrgList() {
		return orgList;
	}
	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}
	
	
}
